<template>
  <div class="prescription-handle">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="处方编号" prop="prescriptionNo">
            <el-input v-model="form.prescriptionNo" placeholder="请输入处方编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="患者" prop="userId">
            <el-select
              v-model="form.userId"
              placeholder="请选择患者"
              filterable
              remote
              :remote-method="searchPatients"
              style="width: 100%"
            >
              <el-option
                v-for="patient in patientList"
                :key="patient.id"
                :label="patient.name"
                :value="patient.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="处方类型" prop="type">
            <el-select  v-model="form.type" placeholder="请选择类型" style="width: 100%" @change="handleTypeChange">
              <el-option label="西药" :value="1" />
              <el-option label="中药" :value="2" />
              <el-option label="中成药" :value="3" />
              <el-option label="生物制品" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总金额" prop="totalAmount">
            <el-input-number
              v-model="form.totalAmount"
              :min="0"
              :precision="2"
              placeholder="请输入总金额"
              style="width: 100%"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 药品选择 -->
      <el-form-item  label="选择药品" prop="medicines">
        <el-select
          v-model="medicinesIds"
          multiple
          remote
          placeholder="请选择药品"
          style="width: 100%"
          value-key="id"
          @change="updateMedicine"
        >
          <el-option
            v-for="item in medicineOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span>{{ item.name }}</span>
              <span style="color: #999; font-size: 13px">
                {{ item.specification }} | ¥{{ item.sellingPrice }}
              </span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 已选药品列表 -->
      <div v-if="form.medicines && form.medicines.length > 0" class="selected-medicines">
        <el-table :data="form.medicines" border style="width: 100%; margin: 15px 0;">
          <el-table-column prop="name" label="药品名称" min-width="150" />
          <el-table-column prop="specification" label="规格" width="120" />
          <el-table-column label="用法用量" width="300">
            <template #default="{ row }">
              <el-input-number 
                v-model="row.quantity" 
                :min="1" 
                :max="999"
                style="width: 150px;"
                @change="calculateTotal"
              />
              {{ row.unit }}
              <el-select 
                v-model="row.medicineUsage" 
                placeholder="用法"
                style="width: 100px; margin: 0 10px;"
              >
                <el-option label="口服" value="口服" />
                <el-option label="外用" value="外用" />
                <el-option label="静脉注射" value="静脉注射" />
                <el-option label="肌肉注射" value="肌肉注射" />
                <el-option label="皮下注射" value="皮下注射" />
                <el-option label="含服" value="含服" />
                <el-option label="嚼服" value="嚼服" />
                <el-option label="滴眼" value="滴眼" />
                <el-option label="滴鼻" value="滴鼻" />
                <el-option label="外敷" value="外敷" />
                <el-option label="雾化吸入" value="雾化吸入" />
                <el-option label="贴敷" value="贴敷" />
                <el-option label="冲服" value="冲服" />
              </el-select>
              <el-select 
                v-model="row.frequency" 
                placeholder="频次"
                style="width: 100px;"
              >
                <el-option label="每日一次" value="每日一次" />
                <el-option label="每日两次" value="每日两次" />
                <el-option label="每日三次" value="每日三次" />
                <el-option label="每日四次" value="每日四次" />
                <el-option label="每周一次" value="每周一次" />
                <el-option label="每周两次" value="每周两次" />
                <el-option label="每周三次" value="每周三次" />
                <el-option label="隔日一次" value="隔日一次" />
                <el-option label="每晨一次" value="每晨一次" />
                <el-option label="每晚一次" value="每晚一次" />
                <el-option label="饭前" value="饭前" />
                <el-option label="饭后" value="饭后" />
                <el-option label="必要时" value="必要时" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="sellingPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.sellingPrice }}
            </template>
          </el-table-column>
          <el-table-column label="小计" width="100">
            <template #default="{ row }">
              ¥{{ (row.sellingPrice * (row.quantity || 1)).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template #default="{ $index }">
              <el-button 
                type="danger" 
                link
                @click="removeMedicine($index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="prescription-total">
          <span class="total-label">处方总金额：</span>
          <span class="total-amount">¥{{ form.totalAmount.toFixed(2) }}</span>
        </div>
      </div>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    
    <div class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        确定
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/api/request'
import { getMedicineList } from '@/api/business'

// 定义props
const props = defineProps({
  prescriptionData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  patientList: {
    type: Array,
    default: () => []
  }
})

// 定义emits
const emit = defineEmits(['close'])

// 响应式数据
const submitting = ref(false)
const formRef = ref()
const patientList = ref([])
const medicineLoading = ref(false)
const medicineOptions = ref([])
const medicinesIds = ref([])

// 表单数据
const form = reactive({
  id: null,
  prescriptionNo: '',
  userId: null,
  type: null,
  totalAmount: 0,
  remark: '',
  medicines: [],
  doctorId: null,  // 将由后端自动填充
  departmentId: null,  // 将由后端自动填充
  status: 0,  // 默认为待审核状态
  createTime: null,  // 将由后端自动填充
  updateTime: null   // 将由后端自动填充
})

// 表单验证规则
const rules = {
  prescriptionNo: [
    { required: true, message: '请输入处方编号', trigger: 'blur' },
    { min: 4, max: 20, message: '处方编号长度应在4-20个字符之间', trigger: 'blur' }
  ],
  userId: [
    { required: true, message: '请选择患者', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择处方类型', trigger: 'change' }
  ],
  totalAmount: [
    { required: true, message: '请输入总金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '总金额不能小于0', trigger: 'blur' }
  ],
  remark: [
    { max: 500, message: '备注不能超过500个字符', trigger: 'blur' }
  ]
}

// 搜索患者
const searchPatients = async (query) => {
  if (query) {
    try {
      const response = await request.get('/admin/users', {
        params: { role: 1, name: query }
      })
      if (response.code === 200) {
        if (Array.isArray(response.data)) {
          patientList.value = response.data
        } else {
          patientList.value = response.data.list || []
        }
      }
    } catch (error) {
      console.error('搜索患者失败:', error)
    }
  }
}

// 获取患者列表
const fetchPatients = async () => {
  try {
    const response = await request.get('/admin/users', {
      params: { role: 1 }
    })
    if (response.code === 200) {
      if (Array.isArray(response.data)) {
        patientList.value = response.data
      } else {
        patientList.value = response.data.list || []
      }
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
  }
}

// 修改 
const updateMedicine = () => {
  let medicines = medicineOptions.value.filter(item => medicinesIds.value.includes(item.id))
  console.log(medicines,'medicines')
  // 将选中的药品添加到 form.medicines
  form.medicines = medicines.map(medicine => ({
    
    id: medicine.id,
    name: medicine.name,
    specification: medicine.specification,
    unit: medicine.unit,
    sellingPrice: medicine.sellingPrice,
    quantity: 1,
    medicineUsage: '口服',
    frequency: '每日三次'
  }))
  
  // 计算总金额
  calculateTotal()
}

// 初始化表单数据
const initFormData = async () => {
  if (props.isEdit && props.prescriptionData) {
    try {
      // 获取处方详情
      const response = await request.get(`/business/prescription/${props.prescriptionData.id}`)
      if (response.code === 200) {
        const prescriptionDetail = response.data
        Object.assign(form, {
          id: prescriptionDetail.id,
          prescriptionNo: prescriptionDetail.prescriptionNo,
          userId: prescriptionDetail.userId,
          type: prescriptionDetail.type,
          totalAmount: prescriptionDetail.totalAmount,
          remark: prescriptionDetail.remark,
          medicines: prescriptionDetail.prescriptionDetails?.map(detail => ({
            id: detail.medicineId,
            name: detail.medicineName,
            specification: detail.medicineSpecification,
            sellingPrice: detail.unitPrice,
            quantity: detail.quantity,
            medicineUsage: detail.medicineUsage,
            frequency: detail.frequency,
            unit: detail.medicineUnit
          })) || []
        })

        // 如果有处方明细，获取完整的药品信息
        if (prescriptionDetail.prescriptionDetails && prescriptionDetail.prescriptionDetails.length > 0) {
          const medicineIds = prescriptionDetail.prescriptionDetails.map(detail => detail.medicineId)
          medicinesIds.value = medicineIds
          console.log(medicinesIds.value,'medicineIds')
          const medicineResponse = await getMedicineList({
            ids: medicineIds.join(',')
          })
          if (medicineResponse.code === 200) {
          console.log(medicineResponse.data.list,'medicineResponse.data.list')
            medicineOptions.value = medicineResponse.data.list || []
            // updateMedicine()
          }
        }
      } else {
        ElMessage.error(response.message || '获取处方详情失败')
      }
    } catch (error) {
      console.error('获取处方详情失败:', error)
      ElMessage.error('获取处方详情失败')
    }
  } else {
    Object.assign(form, {
      id: null,
      prescriptionNo: '',
      userId: null,
      type: null,
      totalAmount: 0,
      remark: '',
      medicines: []
    })
    medicinesIds.value = [] // 清空已选药品
  }
}

// 处理取消
const handleCancel = () => {
  emit('close')
}

// 搜索药品
const searchMedicines = async (query) => {
  if (query !== '') {
    medicineLoading.value = true
    try {
      const response = await getMedicineList({
        category: form.type,
        page: 1,
        size: 20
      })
      if (response.code === 200) {
        medicineOptions.value = response.data.list || []
      }
    } catch (error) {
      console.error('搜索药品失败:', error)
    } finally {
      medicineLoading.value = false
    }
  } else {
    medicineOptions.value = []
  }
}

// 处方类型改变时清空药品
const handleTypeChange = () => {
  form.medicines = []
  form.totalAmount = 0
  medicineOptions.value = []
  medicinesIds.value = [] // 清空已选药品
  searchMedicines()
}

// 计算总金额
const calculateTotal = () => {
  form.totalAmount = form.medicines.reduce((total, medicine) => {
    return total + (medicine.sellingPrice * (medicine.quantity || 1))
  }, 0)
}

// 监听药品变化
watch(() => form.medicines, (newVal) => {
  // 为新添加的药品设置默认值
  newVal.forEach(medicine => {
    if (!medicine.quantity) {
      medicine.quantity = 1
    }
    if (!medicine.medicineUsage) {
      medicine.medicineUsage = '口服'
    }
    if (!medicine.frequency) {
      medicine.frequency = '每日三次'
    }
  })
  calculateTotal()
}, { deep: true })

// 添加删除药品方法
const removeMedicine = (index) => {
  form.medicines.splice(index, 1)
  medicinesIds.value.splice(index, 1) // 同时从 medicinesIds 中移除
  calculateTotal()
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if ((form.type === 1 || form.type === 2) && form.medicines.length === 0) {
      ElMessage.warning('请至少选择一个药品')
      return
    }
    
    submitting.value = true
    
    const data = {
      ...form,
      prescriptionDetails: form.medicines.map(medicine => ({
        medicineId: medicine.id,
        medicineName: medicine.name,
        medicineSpecification: medicine.specification,
        medicineUnit: medicine.unit,
        quantity: medicine.quantity || 1,
        medicineUsage: medicine.medicineUsage || '口服',
        frequency: medicine.frequency || '每日三次',
        unitPrice: medicine.sellingPrice,
        amount: medicine.sellingPrice * (medicine.quantity || 1)
      }))
    }
    
    const url = '/business/prescription'
    const method = props.isEdit ? 'put' : 'post'
    
    const response = await request[method](url, data)
    
    if (response.code === 200) {
      ElMessage.success(props.isEdit ? '处方更新成功' : '处方添加成功')
      emit('close', 'success')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

// 组件挂载时初始化数据
onMounted(async () => {
  await initFormData()
  await fetchPatients()
  // 如果有传入的患者列表，优先使用
  if (props.patientList.length > 0) {
    patientList.value = props.patientList
  }
})
</script>

<style scoped>
.prescription-handle {
  padding: 20px 0;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 600;
}

.selected-medicines {
  margin: 15px 0;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.prescription-total {
  margin-top: 15px;
  text-align: right;
  padding-right: 20px;
}

.total-label {
  font-size: 14px;
  color: #606266;
}

.total-amount {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
  margin-left: 8px;
}

:deep(.el-input-number.is-controls-right .el-input__wrapper) {
  padding-right: 35px !important;
}
</style> 